package com.lap.framework.validate.validator;

import com.lap.framework.validate.annotation.Dict;
import com.lap.framework.validate.exception.NotFoundException;
import com.lap.framework.validate.manager.DictValidatorManager;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.ServiceLoader;

/**
 * 字典验证器
 *
 * @author Shuisheng Lao(劳水生)
 * @version 0.0.1
 * @see Dict
 * @see DictValidatorManager
 */
public class DictValidator implements ConstraintValidator<Dict, Integer> {

  private String code;

  private DictValidatorManager dictValidatorManager;

  @Override
  public void initialize(Dict constraintAnnotation) {
    this.code = constraintAnnotation.code();
    ServiceLoader<DictValidatorManager> serviceLoader =
        ServiceLoader.load(DictValidatorManager.class);
    this.dictValidatorManager =
        serviceLoader.findFirst().orElseThrow(() -> new NotFoundException("字典服务类不存在,请处理"));
  }

  @Override
  public boolean isValid(Integer value, ConstraintValidatorContext context) {
    return value != null && dictValidatorManager.validate(code, value);
  }
}
